<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\model\Image;
use app\admin\model\Libraryopen;

use think\Db;
use think\Exception;
use think\Request;

class Library extends Base
{

    protected $redirect = '';

    public function _initialize() {
        parent::_initialize();

        $this->redirect = 'admin/library/index';
        $this->searchFields = [
            'name' => [
                'label'     => '名称',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];
    }

    public function index(){
        $request = $this->request;
        $param = $request->param();

        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }

        if($request->isAjax()){
            $model = model($this->model);
            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);

            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($this->defaultWhere, $where);
            }
            /*if($this->defaultOrder){
                $model = $model->order($this->defaultOrder);
            }*/
            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            $count = $model->where($where)->count();

            foreach ($list as $item) {
                $item['createOper'] = \app\admin\model\User::where('id', $item['createOper'])->value('p_name');
                // 职务
                //$department = \app\admin\model\Department::where(['id' => $item->departmentId])->value('name');
                //$item->department = $department;
            }

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    public function add(Request $request) {

        return $this->view->fetch('add', []);
    }

    public function edit(Request $request) {
        $id = $request->param('id');
        $model = model($this->model);
        $where['id'] = $id;
        $info = $model->where($where)->find();
        $this->assign('info',$info);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        return $this->view->fetch('edit', [
            'info' => $info
        ]);
    }

    public function savePost(Request $request, $redirect = ''){
        $model = model($this->model);
        if ($request->isPost()) {
            $data = $request->param();
            dump($data);exit;

            try {
                Db::startTrans();
                if(isset($data['id']) && $data['id']){
                    $data['updateDate'] = date('Y-m-d H:i:s', time());
                    $data['updateOper'] = $this->admin->id;

                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                    if($result !== false) {
                        // 保存公开人员
                        $res = $this->saveLibraryopen($data);
                        if($res['code'] != 1){
                            Db::rollback();
                            return $this->error($res['msg']);
                        }

                        Db::commit();
                        return $this->success('保存成功！', $this->redirect);
                    } else {
                        Db::rollback();
                        return $this->error($model->getError());
                    }
                }

                $data['id'] = Helper::getUUID();
                $data['createDate'] = date('Y-m-d H:i:s', time());
                $data['createOper'] = $this->admin->id;
                $result = $model->save($data);

                if($result !== false) {
                    // 保存公开人员
                    $res = $this->saveLibraryopen($data);
                    if($res['code'] != 1){
                        Db::rollback();
                        return $this->error($res['msg']);
                    }

                    Db::commit();
                    return $this->success('添加成功！', $this->redirect);
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('请求方式错误！');
        }
    }

    /**
     * 保存公开人员
     */
    protected function saveLibraryopen($params) {
        if(!$params){
            return ['code' => 0, 'msg' => '参数错误'];
        }

        $libraryId = $params['id'];
        $model = new Libraryopen();

        if($params['openType'] == 1) {
            $res = $model->where('libraryId', $libraryId)->delete();
            if($res === false){
                return ['code' => 0, 'msg' => $model->getError()];
            }

            $userIds = explode(',', $params['openuserIds']);
            foreach ($userIds as $userId) {
                $result = $model->insert(['libraryId' => $libraryId, 'userId' => $userId]);
            }
        } else {
            $result = $model->where('libraryId', $libraryId)->delete();
        }

        if ($result !== false) {
            return ['code' => 1, 'msg' => '保存成功'];
        } else {
            return ['code' => 0, 'msg' => $model->getError()];
        }
    }

    public function delete(Request $request) {
        $id = $this->request->param('id');
        $model = model($this->model);
        $where = [
            'id' => $id
        ];
        $result = $model->where($where)->delete();

        if($result !== false) {
            return $this->success('删除成功', $this->redirect);
        } else {
            return $this->error('删除失败 !');
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['typeId']) && $filter['typeId']){
                $where['typeId'] = $filter['typeId'];
            }
            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }

    /**
     * 成员列表
     */
    public function userList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('User');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            
            if(isset($filter['name']) && $filter['name']){
                $where['p_name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        $list = $model->alias('a')->where($where)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 公开人员 列表
     */
    public function openuserList(){
        $request = $this->request;
        $param = $request->param();
        $model = new Libraryopen();

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        if(empty($param['id'])){
            $result = [
                'status' => '0',
                'draw' => $param['draw'],
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
            ];
            return json($result);
        }
        $where = [
            'libraryId' => $param['id']
        ];

        $join = [
            ['__USER__ u', 'a.userId = u.id'],
        ];
        $field = 'a.*, u.p_imgUrl, u.p_name';
        $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->join($join)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

}
